package handlers

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"video/cache"
	"video/models"
	"video/pkg"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "用户名或密码为空",
		})
		return
	}

	login := "login" + username
	count, _ := cache.Rdb.Get(cache.Ctx, login).Int()
	if count >= 3 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "密码错误次数过多，禁止登录",
		})
		return
	}

	var user models.User
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}

	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, login)
		if count == 2 {
			cache.Rdb.Set(cache.Ctx, login, 3, 0)
			c.JSON(http.StatusOK, gin.H{
				"code": 500,
				"msg":  "密码错误三次以上，禁止登录",
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}
